﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Transform Pixel coordinates by given delegate
    /// </summary>
    public class ImageTransformation : BaseImageFilter
    {
        public delegate void ImageTransformationDelegate(int x, int y, out int xTransform, out int yTransform);
        protected ImageTransformationDelegate m_ImageTransformationDelegate = null;

        /// <summary>
        /// 
        /// </summary>
        public ImageTransformation()
        {
            m_ImageTransformationDelegate = new ImageTransformationDelegate(
                delegate(int x, int y, out int xTransform, out int yTransform)
                {
                    xTransform = (int)Math.Sqrt(x)+x;
                    yTransform = (int)Math.Sqrt(y)+y;
                }
            );
        }

        /// <summary>
        /// Used to create a deep copy...
        /// </summary>
        /// <param name="_imageTransformation"></param>
        internal ImageTransformation(ImageTransformation _imageTransformation)
        {
        }

        /// <summary>
        /// Imagetransformationdelegate...
        /// </summary>
        public ImageTransformationDelegate ImageTransformationFormula
        {
            get { return m_ImageTransformationDelegate; }
            set { m_ImageTransformationDelegate = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmapCloned = (UnsafeBitmap)_bitmap.Clone();
            _bitmap.Clear();
            int nWidth = _bitmap.Width;
            int nHeight = _bitmap.Height;
            
            int xTransformed = 0;
            int yTransformed = 0;

            for (int y = 0; y < nHeight; y++)
            {
                for (int x = 0; x < nWidth; x++)
                {
                    Color color = bitmapCloned.GetPixel(x, y);
                    m_ImageTransformationDelegate(x, y, out xTransformed, out yTransformed);
                    xTransformed = ImageMath.Clamp(xTransformed, 0, nWidth);
                    yTransformed = ImageMath.Clamp(yTransformed, 0, nHeight);
                    _bitmap.SetPixel(xTransformed, yTransformed, color);
                }
            }
            return _bitmap;
        }

        /// <summary>
        /// Clone this instance
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new ImageTransformation(this);
        }
    }
}
